﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using CrazyClient.Classes.Assets;

namespace CrazyClient
{
    public class AssetHandler
    {
        public AssetHandler()
        {
            _assets = new AssetList();
        }
        public static string BaseFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//CrazyWorship";
        private string assetPath;
        public string AssetPath
        {
            get { return assetPath; }
        }
        public void Start(string uri)
        {
            assetPath = BaseFolder + "\\Client\\" + uri.Replace("http://", "").Replace("/", "").Replace("\\", "").Replace(":", "") + "\\";
            LoadAssetInfo();
        }
        private void LoadAssetInfo()
        {
            _assets.Clear();
            if (!Directory.Exists(assetPath))
                Directory.CreateDirectory(assetPath);
           //TODO: _assets.ReadXml(assetPath + "assets.dat");
        }
        public SongAsset GetSongAsset(string fileName)
        {
            SongAsset a = null;
            if (File.Exists(assetPath + fileName))
            {
                a = new SongAsset(assetPath + fileName);
            }
            return a;
        }
        AssetList _assets;

        public bool AssetsNeedsUpdate(string fileName, DateTime lastUpdate)
        {
            AssetList.AssetsRow r = _assets.Assets.FindByFileName(fileName);
            if (r == null) return true;
            return (r.LastUpdated < lastUpdate);
        }
        public void AssetUpdate(string fileName, DateTime lastUpdate, Stream songXml)
        {
            AssetList.AssetsRow r = _assets.Assets.FindByFileName(fileName);
            if (r != null)
                _assets.Assets.RemoveAssetsRow(r);
            string saveFile = this.assetPath + fileName;
            string saveFolder = saveFile.Remove(saveFile.LastIndexOf("/"));
            if (!Directory.Exists(saveFolder))
                Directory.CreateDirectory(saveFolder);
            FileStream stream = new FileStream(saveFile, FileMode.Create);

            //            StreamReader s = new StreamReader(songXml,.UTF8);
            //          StreamWriter write = new StreamWriter(stream,Encoding.UTF8);


            while (true)
            {
                int i = songXml.ReadByte();
                if (i == -1) break;
                stream.WriteByte((byte)i);
            }
            stream.Close();
            _assets.Assets.AddAssetsRow(fileName, lastUpdate);
        }
    }
}
